﻿namespace Leetcode.N0992;

public class Solution
{
    public int SubarraysWithKDistinct(int[] nums, int k)
    {
        return Subarrays(nums, k) - Subarrays(nums, k - 1);
    }

    private int Subarrays(int[] nums, int k)
    {
        int[] count = new int[nums.Length + 1];
        int right = 0;
        int left = 0;
        int result = 0;
        int dightCount = 0;

        while (right < nums.Length)
        {
            if (count[nums[right]] == 0)
            {
                dightCount++;
            }

            count[nums[right]]++;
            right++;

            while (dightCount > k)
            {
                count[nums[left]]--;
                if (count[nums[left]] == 0)
                {
                    dightCount--;
                }
                left++;
            }
            result += right - left;
        }

        return result;
    }
}
